import express from 'express'
import { Response, Request } from "express"

const router = express.Router()

import { success, failure } from '../utils/responses'
import { Article } from "../entities/Article"
import { AppDataSource } from "../config/database"
import { BadRequest, NotFound } from "http-errors"
import { FindManyOptions } from "typeorm";
import { Video } from "../entities/Video";
import { getFileDownloadUrl } from "../utils/qiniuyun";

/**
 * 查询文章列表
 */
router.get('/', async function (req: Request, res: Response) {
  try {
    const query = req.query

    if (isNaN(+query.categoryId) || !(+query.categoryId)) {
      throw new BadRequest("请传入合法的分类id")
    }

    const categoryId = Number(query.categoryId) // 分类id
    console.log('categoryId: ' + categoryId)
    const currentPage = Math.abs(Number(query.currentPage)) || 1 // 当前页
    const pageSize = Math.abs(Number(query.pageSize)) || 10 // 每页条数
    const offset = (currentPage - 1) * pageSize // 偏移量

    const articleRepository = AppDataSource.getRepository(Article)
    const findOptions: FindManyOptions = {
      relations: {
        category: true,
        author: true,
        video: true
      },
      where: {
        category: {
          id: categoryId
        }
      },
      order: {
        updatedAt: "DESC"
      },
      skip: offset,
      take: pageSize
    }

    // 如果分类id为1，表示推荐，则需要根据点赞数降序排列，且应展示全部内容
    if (categoryId === 1) {
      findOptions.order = {
        likeCount: "DESC",
        updatedAt: "DESC"
      }
      delete findOptions.where // 目的是展示所有内容，不需要根据分类id过滤数据
    }

    const [articles, totalCount] = await articleRepository.findAndCount(findOptions)
    console.log(articles)

    const videoRepository = AppDataSource.getRepository(Video)
    // 去除不需要的字段
    const filterArticles = await Promise.all(articles.map(async article => {
      const { id, title, category, coverImages, video, author, updatedAt } = article;
      // 检查video链接是否过期，若过期则更新
      if (video && video.videoUrl) {
        const videoUrl = video.videoUrl
        const url = videoUrl.split('?')[0]
        const filename = 'video/' + url.slice(url.lastIndexOf('/') + 1) // 拿到文件名
        video.videoUrl = getFileDownloadUrl(filename) // 获取最新的地址
        await videoRepository.save(video) // 更新头像
      }

      return {
        id,
        title,
        coverImages,
        video,
        updatedAt,
        category: {
          id: category.id,
          name: category.name,
        },
        author: {
          id: author.id,
          username: author.username,
        }
      }
    }))

    success(res, '查询文章列表成功', {
      articles: filterArticles,
      pagination: {
        totalPage: Math.ceil(totalCount / pageSize),
        currentPage,
        pageSize,
        totalCount
      }
    })
  } catch (error) {
    failure(res, error)
  }
})

/**
 * 查询文章详情
 */
router.get('/:id', async function (req: Request, res: Response) {
  try {
    const articleId = Number(req.params.id)
    if (isNaN(articleId)) throw new BadRequest("请传入合法的文章id")

    const articleRepository = AppDataSource.getRepository(Article)
    const article = await articleRepository.findOne({
      relations: {
        author: true,
        video: true
      },
      where: {
        id: articleId
      }
    })

    if (!article) {
      throw new NotFound(`ID为${articleId}的文章未找到`)
    }
    const { id, username } = article.author // 取出作者的id和用户名
    delete article.author // 删除article的author字段
    success(res, '查询文章详情成功', {
      ...article,
      author: {
        id,
        username
      }
    })
  } catch (error) {
    failure(res, error)
  }
})

export default router
